package org.example.cdpcrpbackend.util.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import org.example.cdpcrpbackend.domain.Student;
import org.example.cdpcrpbackend.service.StudentService;

import java.util.List;

public class StudentUploadListener implements ReadListener<Student> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<Student> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private final StudentService studentService;


    public StudentUploadListener(StudentService studentService) {
        this.studentService = studentService;
    }


    @Override
    public void invoke(Student data, AnalysisContext context) {
        cachedDataList.add(data);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
//        cachedDataList.forEach(System.out::println);
        studentService.saveBatch(cachedDataList);
    }
}
